/*
 *
 * Copyright (C) 2012 Walter Lütgenau
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package offset.nodes.client.virtual.model.jcr;

import java.io.Serializable;
import offset.nodes.Constants;

/**
 *
 * @author Walter Lütgenau
 */
public class QName implements Comparable, Cloneable, Serializable {

    String namespaceURI;
    String localName;
    public static final QName ANY_NAME = new QName("", "*");
    public static final QName NT_HIERARCHY_NODE = new QName(Constants.JCR_NS_NT, "hierarchyNode");
    public static final QName NT_BASE = new QName(Constants.JCR_NS_NT, "base");
    public static final QName NAME_PROPERTY = new QName(null, "NAME");

    public QName(String namespaceURI, String localName) {
        this.namespaceURI = namespaceURI;
        this.localName = localName;
    }
    
    @Override
    public Object clone() {
        QName clone = new QName(new String(namespaceURI), new String(localName));
        return clone;
    }

    public int compareTo(Object o) {
        return toString().compareTo(o.toString());
    }
    
    public boolean equals(Object o) {
        return toString().equals(o.toString());
    }
    
    public int hashCode() {
        return toString().hashCode();
    }

    public String getLocalName() {
        return localName;
    }

    public void setLocalName(String localName) {
        this.localName = localName;
    }

    public String getNamespaceURI() {
        return namespaceURI;
    }

    public void setNameSpaceUri(String namespaceURI) {
        this.namespaceURI = namespaceURI;
    }
    
    public String toString() {
        try {
            return "{" + namespaceURI + "}" + localName;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        } 
    }

    public static QName valueOf(String qname) {
        if ( qname.equals("*"))
            return ANY_NAME;
        if ( qname == null || qname.length() == 0)
            return null;

        if (qname.charAt(0) == '{') {
            int i = qname.indexOf('}');

            if (i == -1)
                throw new IllegalArgumentException("invalid QName literal");

            if (i == qname.length() - 1)
                return null;
            else
                return new QName(qname.substring(1, i), qname.substring(i + 1));
        } else
            return null;
    }
}
